# coding: utf-8
# author: dengpanxiao(@126.com)
import db

# 定义元类
class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        __table__ = cls.__table__   # 表名
        __mapping__ = cls.__mapping__ # 类属性与表属性对应表，key为类属性，value为表列名和描述的对象
        __primary_key__ = cls.__primary_key__  # 主键
        attrs['__table__'] = __table__
        # attrs['__mapping__']  = __mapping__
        for k in attrs:
            if attrs[k]
        attrs['__primary_table__']  = __primary_key__
        return type.__new__(cls, name, bases, attrs)

# 基类
class Model(dict):
    __metaclass__ = ModelMetaclass

    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    def __getattr__(self, item):
        if item not in self:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % item)
        else:
            return self[item]

    def __setattr__(self, key, value):
        self[key] = value

    # 插入
    def insert(self):
        params = {}
        for k, v in self.__mapping__.iteritems():
            params[v.name] = getattr(self,k)
        db.insert(self.__table__, **params)
        return self

    # 按主键查询
    @classmethod
    def get(cls, item):
        result = db.select_one('selelct * from %s where %s== ?' % (cls.__table__, cls.__primary_key__.name), item)
        return cls(**result) if result is not None

    def delete(self, **kw):
        pass

    def change(self,**kw):


# 整型元素类
class IntegerField():
    pass


# 字符型元素类
class StringField():
    pass

class User(Model):
    __table__ = 'users'
    id = IntegerField(primary_key=True)
    name = StringField()